<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select class="handle-input mr10" v-model="search.kindId" placeholder="资金类型" @change="getData()">
          <el-option v-for="item in kindList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-input v-model="search.mobile" placeholder="手机号" class="handle-input mr10" clearable></el-input>
        <span class="mr10">
          <el-date-picker v-model="time" type="datetimerange" format="YYYY-MM-DD HH:mm:ss" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </span>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="showBox()">添加</el-button>
        <el-button type="primary" @click="showExportDialog">导出</el-button>
        <!-- <el-button type="primary" @click="reload()">刷新页面</el-button> -->
      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="user" label="用户ID">
          <template #default="scope">
            <span>{{ scope.row.user || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户名">
          <template #default="scope">
            <span>{{ scope.row.name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="资金类型">
          <template #default="scope">
            <span>{{ getKindName(scope.row.kindId) || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="context" label="交易内容">
          <template #default="scope">
            <span>{{ scope.row.context || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额">
          <template #default="scope">
            <span>{{ scope.row.money || '-' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="type" label="类型">
          <template #default="scope">
            <span>{{ getTypeName(scope.row.type) || '-' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '0'">减</el-tag>
            <el-tag v-else-if="scope.row.status == '1'">加</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="时间" :formatter="dateFormat">
          <template #default="scope">
            <span>{{ scope.row.time ? dateFormat(scope.row, { property: 'time' }) : '-' }}</span>
          </template>
        </el-table-column>

      </el-table>
      <div class="pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="query.pageIndex"
          :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>
    <!-- 新增弹出框 -->
    <el-dialog title="新增资金明细" v-model="showAddUser" width="60%">
      <el-form ref="form" :model="list" label-width="100px">
        <el-form-item label="资金类型">
          <el-select class="handle-input mr10" v-model="list.kindId" placeholder="选择资金类型">
            <el-option v-for="item in kindList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择用户">
          <div style="display: flex; align-items: center;">
            <el-input v-model="selectedUserName" placeholder="请选择用户" readonly style="margin-right: 10px;"></el-input>
            <el-button type="primary" @click="showSelectUser = true" style="margin-right: 10px;">选择用户</el-button>
            <el-button v-if="selectedUserName" type="danger" @click="clearSelectedUser">清除</el-button>
          </div>
        </el-form-item>
        <!-- <el-form-item label="交易内容">
          <el-input v-model="list.context" placeholder="请输入交易内容"></el-input>
        </el-form-item> -->
        <el-form-item label="交易金额">
          <el-input v-model="list.money" type="number" placeholder="请输入交易金额"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="list.type" placeholder="请选择类型" class="handle-input">
            <el-option label="手动操作" :value="0"></el-option>
            <!-- <el-option label="客资奖励" :value="1"></el-option>
            <el-option label="量房" :value="2"></el-option>
            <el-option label="邀约进店" :value="3"></el-option>
            <el-option label="交定奖励" :value="4"></el-option>
            <el-option label="转合同奖励" :value="5"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="list.status">
            <el-radio :label="0">减</el-radio>
            <el-radio :label="1">加</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddUser = false">取 消</el-button>
          <el-button type="primary" @click="append">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择用户弹窗 -->
    <selectUser v-model="showSelectUser" :multiple="false" :selectedUserIds="list.user ? [list.user] : []"
      @confirm="handleUserSelect" />

    <!-- 导出选择用户弹窗 -->
    <selectUser v-model="showExportSelectUser" :multiple="false" :selectedUserIds="eList.user ? [eList.user] : []"
      @confirm="handleExportUserSelect" />
    <!-- 导出框 -->
    <el-dialog title="导出资金明细" v-model="showExport" width="40%">
      <el-form ref="form" :model="eList" label-width="100px">
        <el-form-item label="资金类型">
          <el-select class="handle-input mr10" v-model="eList.kindId" placeholder="选择资金类型">
            <el-option v-for="item in kindList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择用户">
          <div style="display: flex; align-items: center;">
            <el-input v-model="exportSelectedUserName" placeholder="请选择用户" readonly
              style="margin-right: 10px;"></el-input>
            <el-button type="primary" @click="showExportSelectUser = true" style="margin-right: 10px;">选择用户</el-button>
            <el-button v-if="exportSelectedUserName" type="danger" @click="clearExportSelectedUser">清除</el-button>
          </div>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker v-model="etime" type="datetimerange" format="YYYY-MM-DD HH:mm:ss" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showExport = false">取 消</el-button>
          <el-button type="primary" @click="confirmExport">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导入框 -->
    <el-dialog title="导入资金表格" v-model="showImport" width="40%">
      <el-form ref="form" :model="eList" label-width="100px">
        <el-form-item label="上传文件：">
          <el-upload class="upload-demo" drag :http-request="uploadFileMethod"
            action="https://jsonplaceholder.typicode.com/posts/" multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImport = false">取 消</el-button>
          <el-button type="primary" @click="confirmImport">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { api, apiEx, upload } from "../../../api/index";
import { formatDate } from "../../../common/data";
import moment from "moment";
import selectUser from "../../../components/selectUser.vue";

export default {
  inject: ["reload"],
  components: {
    selectUser
  },
  filters: {
    formatDate(time) {
      time = time * 1000;
      let date = new Date(time);
      console.log(new Date(time));
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },
  name: "basetable",
  data() {
    return {
      query: {
        pageNo: 1,
      },
      time: "",
      kindList: [],
      statementList: [],
      search: {
        kindId: "",
        mobile: "",
      },
      tableData: [],
      pageTotal: 0,
      list: {},
      showAddUser: false,
      showSelectUser: false,
      selectedUserName: "",
      showExportSelectUser: false,
      exportSelectedUserName: "",
      isOfficial: localStorage.getItem('isOfficial'),
      showExport: false,
      showImport: false,
      eList: {},
      etime: "",
      excelUrl: ''
    };
  },
  async created() {
    await this.getKindList()
    // this.getStatement()
    this.getData();
  },
  mounted() { },
  methods: {
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    //显示新增框
    showBox() {
      this.showAddUser = true;
      this.list = {};
      this.selectedUserName = "";
    },

    // 处理用户选择
    handleUserSelect(users) {
      if (users && users.length > 0) {
        const user = users[0];
        this.list.user = user.userId;
        this.list.loginName = user.loginName; // 保存loginName到this.list
        // 显示格式：用户名(用户id)
        const userName = user.nickname || user.loginName || '未知用户';
        this.selectedUserName = `${userName}(${user.userId})`;
      }
    },

    // 清除选中的用户
    clearSelectedUser() {
      this.list.user = "";
      this.selectedUserName = "";
    },

    // 处理导出用户选择
    handleExportUserSelect(users) {
      if (users && users.length > 0) {
        const user = users[0];
        this.eList.user = user.userId;
        // 显示格式：用户名(用户id)
        const userName = user.nickname || user.loginName || '未知用户';
        this.exportSelectedUserName = `${userName}(${user.userId})`;
      }
    },

    // 清除导出选中的用户
    clearExportSelectedUser() {
      this.eList.user = "";
      this.exportSelectedUserName = "";
    },

    // 获取资金类型名称
    getKindName(kindId) {
      const kind = this.kindList.find(item => item.id === kindId);
      return kind ? kind.name : '';
    },

    // 获取类型名称
    getTypeName(type) {
      const typeMap = {
        0: '手动操作',
        1: '客资奖励',
        2: '量房',
        3: '邀约进店',
        4: '交定奖励',
        5: '转合同奖励'
      };
      return typeMap[type] || '';
    },
    //新增
    append() {
      if (!this.list.user) {
        this.$message.error('请选择用户');
        return;
      }
      // if (!this.list.context) {
      //   this.$message.error('请输入交易内容');
      //   return;
      // }
      if (!this.list.money) {
        this.$message.error('请输入交易金额');
        return;
      }
      if (this.list.type === undefined || this.list.type === null) {
        this.$message.error('请选择类型');
        return;
      }

      // 在提交接口前将loginName加到参数里
      const params = { ...this.list };
      if (this.list.loginName) {
        params.loginName = this.list.loginName;
      }

      api('/web/cyBer/add', params).then((res) => {
        if (res.code === 2000) {
          this.$message.success(res.message);
          this.list = {};
          this.selectedUserName = "";
          this.getData();
          this.showAddUser = false;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 触发搜索按钮
    handleSearch() {
      this.query.pageNo = 1
      this.getData();
    },
    async getKindList() {
      await api('/web/daKind/s').then((res) => {
        this.kindList = res.data
        // 默认选中第一个资金类型
        if (res.data && res.data.length > 0) {
          this.search.kindId = res.data[0].id
        }
      });
    },
    getStatement() {
      api('/web/cyBer/statement').then((res) => {
        this.statementList = res.data
        this.search.statement = res.data[0].id
      });
    },
    // 获取资金明细列表
    getData() {
      let endTime = this.time && this.time[1] ? formatDate(new Date(this.time[1]), "yyyy-MM-dd hh:mm:ss") : "";
      let startTime = this.time && this.time[0] ? formatDate(new Date(this.time[0]), "yyyy-MM-dd hh:mm:ss") : "";

      const params = {
        limit: 10,
        offset: this.query.pageNo,
        kindId: this.search.kindId,
        endTime: endTime == "NaN-aN-aN aN:aN:aN" ? "" : endTime,
        startTime: startTime == "NaN-aN-aN aN:aN:aN" ? "" : startTime,
      };

      // 添加筛选条件
      if (this.search.mobile) params.mobile = this.search.mobile;

      api('/web/cyBer/list', params).then((res) => {
        // 给没有kindId的数据填上当前筛选的kindId
        this.tableData = res.data.rows.map(item => ({
          ...item,
          kindId: item.kindId || this.search.kindId
        }));
        this.pageTotal = res.data.total;
      });
    },

    // 分页导航
    handlePageChange(val) {
      // console.log(val);
      this.query.pageNo = val;
      this.getData();
    },

    // 显示导出弹窗
    showExportDialog() {
      this.showExport = true;
      this.eList = {};
      this.exportSelectedUserName = "";
      this.etime = "";
    },
    confirmExport() {
      this.showExport = false;
      this.eList.startTime = formatDate(new Date(this.etime[0]), "yyyy-MM-dd");
      this.eList.endTime = formatDate(new Date(this.etime[1]), "yyyy-MM-dd");
      apiEx('/web/cyBer/export', this.eList).then((res) => {
        const blob = new Blob([res]); // 创建blob对象
        const fileName = "资金明细记录.xlsx";
        const elink = document.createElement("a"); // 创建的标签
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob); // 创建url
        document.body.appendChild(elink); // 把 创建的标签追加到body里
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 移除标签
        this.$message({
          message: "导出成功！！！",
          type: "success",
        });
        this.$refs.multipleTable.clearSelection();
      });
    },

    confirmImport() {
      this.showExport = false;
      api('/web/cyBerBalance/imports', {
        excelUrl: this.excelUrl
      }).then((res) => {
        if (res.code === 2000) {
          this.$message.success(res.message);
          this.reload();
        } else {
          this.$message.error(res.message);
        }
      });
    },


    //多图上传
    uploadFileMethod(param) {
      let formData = new FormData();
      if (param.file) {
        formData.append("file", param.file);
      } else {
        formData.append("file", param);
      }
      upload(formData).then((res) => {
        this.excelUrl = `${res.data[0].fileName}`;
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-input {
  width: 220px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}
</style>
